package com.tree.common.util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;

public class MD5Util {
    private static final Logger LOG = LoggerFactory.getLogger(MD5Util.class);
    private static final String[] HEX_DIGITS =
            {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    /**
     * MD5加密
     *
     * @param source
     * @return
     */
    public static String encode(String source) {
        if (StringUtils.isBlank(source)) {
            return null;
        }
        String result = "";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(source.getBytes("utf-8"));
            result = byteArrayToHexString(messageDigest.digest());
        } catch (Exception e) {
            LOG.error("MD5加密异常，source=" + source, e);
        }
        return result.toUpperCase();
    }

    /**
     * 判断加密后是否相等
     *
     * @param source
     * @param sign
     * @return
     */
    public static boolean decode(String source, String sign) {
        if ("".equals(sign) || null == sign) {
            return false;
        }
        String result = encode(source);
        if (null == result) {
            return false;
        }
        return result.equals(sign);
    }

    /**
     * 数组转16进制
     *
     * @param bytes
     * @return
     */
    private static String byteArrayToHexString(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder();
        for (byte tem : bytes) {
            stringBuilder.append(byteToHexString(tem));
        }
        return stringBuilder.toString();
    }

    /**
     * 字节转16进制
     *
     * @param b
     * @return
     */
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return HEX_DIGITS[d1] + HEX_DIGITS[d2];
    }

    public static void main(String[] arg) {
        System.out.println(encode("aaaaa888"));
    }
}